<template>
  <div class="container">
    <div id="mars3dcontent"></div>
    <div class="layercontrol">
      <div class="item" style="display: flex">
        <div style="padding: 1vh">卫星地图</div>
        <el-switch
          style="padding: 1vh"
          size="large"
          v-model="imagemap"
          @change="switchImageLayer"
        />
      </div>
      <div class="item" style="display: flex">
        <div style="padding: 1vh">管网矢量地图</div>
        <el-switch
          style="padding: 1vh"
          size="large"
          v-model="pipemap"
          @change="switchPipLine"
        />
      </div>
    </div>
    <div class="tablecontainer" v-if="panelshow">
        <div class="tableForm">
        <div class="form">
          <div class="select">
            <div style="margin-left: 20px">硬件编号：</div>
            <el-input
              v-model="hardwarenumber"
              style="width: 180px"
              size="large"
              placeholder="请输入"
              @change="numberChange"
            />
            <div>硬件类型：</div>
            <el-input
              v-model="hardwaretype"
              style="width: 180px"
              size="large"
              placeholder="请输入"
              @change="typeChange"
            />
            <div>位置：</div>
            <el-input
              v-model="hardwareposition"
              style="width: 180px"
              size="large"
              placeholder="请输入"
              @change="positionChange"
            />
          </div>
          <div class="bottomlist">
            <el-button
              color="#0000ff"
              style="margin-left: 12px"
              :bg="false"
              size="large"
              plain
              @click="clearSearch"
              >清空</el-button
            >
            <el-button color="#0000ff" size="large" @click="searchTable">查询</el-button>
            <div class="div-button" style="margin-left: 35px" @click="closePanel">
              <img :src="close" />
            </div>
          </div>
        </div>
        <div class="tableposition">
          <el-table
            :data="tableData"
            :cell-style="cellgradeStyle"
            :header-cell-style="headerStyle"
            style="width: 97%"
            @row-dblclick="selectRow"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column property="number" label="硬件编号" width="120" />
            <el-table-column property="type" label="硬件类型" />
            <el-table-column property="position" label="位置" />
            <el-table-column property="status" label="状态" />
            <el-table-column property="waterlevel" label="水位" />
            <el-table-column property="monthwater" label="月最高水位/月最低水位" />
            <el-table-column property="datewater" label="日最高水位/日最低水位" />
            <el-table-column property="handle" label="操作"> 
              
            </el-table-column>
          </el-table>
          <div class="page">
            <div>
              <span style="font-size: 16px">显示{{ pagerow }}条消息 </span>
              <el-input-number
                v-model="currentPage"
                :min="1"
                :max="100"
                controls-position="right"
              />
              <span style="font-size: 16px">
                共 <span style="color: blue">{{ pagenumber }}</span> 条消息</span
              >
            </div>
            <el-pagination
              layout="prev, pager, next"
              :total="pagenumber"
              :page-size="pagerow"
              v-model:current-page="currentPage"
              :change="changePage(value)"
            />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import "mars3d-cesium/Build/Cesium/Widgets/widgets.css"; //依赖的cesium库本身css
import "mars3d/dist/mars3d.css";
import * as mars3d from "mars3d";

import * as echarts from "echarts";
import "echarts-liquidfill";

import { nextTick, onMounted, onUnmounted, reactive, watch } from "vue";
import { mapOptions } from "@/utils/mapOptions";
import { destroyMap, flytoView, transform, LayerCreate, AddGraphic,SptialAnalysis} from "@/utils/Lmap";
import useAppStore from "@/store/modules/app";

import close from "@/assets/trans/close.png";

import waterlevel from '@/assets/trans/waterleve.png';


let map;
let imagemap = ref(false); // 影像地图
let pipemap = ref(false); // 管线地图

let panelshow = ref(true);

let layerpoint = new mars3d.layer.GraphicLayer({ zIndex: 1 }); // 显示线的图层
let layercluster = LayerCreate.createGraphicLayer(); // 聚类图层
let graphicLayer = new mars3d.layer.GraphicLayer({ zIndex: 2 });

let hardwarenumber = ref("");
let hardwaretype = ref("");
let hardwareposition = ref("");

let searchform = reactive({
    number:hardwarenumber.value,
    type:hardwaretype,
    position:hardwareposition
})

let pagerow = ref(4); // 列表显示行
let pagenumber = ref(0); // 行的总数量
let currentPage = ref(1); // 当前页数

let totalData = [];
let tableData = ref([]);

let tileLayer = new mars3d.layer.ArcGisLayer({
  url: "https://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer",
  enablePickFeatures: false,
});

const config = {
  url: "https://www.cqkckc.com/geoserver/hhgw/wms",
  layers: "hhgw:pipe_line",
  parameters: {
    VERSION: "1.1.1",
    transparent: true,
    format: "image/png",
  },
  crs: "EPSG:4326",
};
let wmsLayer = new mars3d.layer.WmsLayer(config);

const store = useAppStore();


watch(currentPage, (newval, oldval) => {
  tableData.value = JSON.parse(
    JSON.stringify(totalData.slice((newval - 1) * 4, (newval - 1) * 4 + 4))
  );
});


// 在map地图上绑定右键菜单
function bindMapDefault(map) {
  // const defaultContextmenuItems = map.getDefaultContextMenu() // 内置的默认右键菜单获取方法
  // map.bindContextMenu(defaultContextmenuItems) // 可以删减defaultContextmenuItems数组内值

  // eslint-disable-next-line no-undef
  const defaultContextmenuItems = map.getDefaultContextMenu() // 是map.getDefaultContextMenu代码相同，用于自定义修改，代码在getDefaultContextMenu.js
  map.bindContextMenu(defaultContextmenuItems) // 可以删减defaultContextmenuItems数组内值
}

function getRandomInt(n) {
    return Math.floor(Math.random() * (n + 1));
}

function getWaterPoint(){
    // let pointgraphic = AddGraphic.addDemoGraphic1(layercluster, transformposition[0]);
    let points = SptialAnalysis.randomPointFromPolygon();
    for (const eachdata of points.features) {
        let attr = {};
        attr.number = "SW00" + getRandomInt(100);
        attr.type = "河湖水位监测仪";
        attr.position = "肖家河";
        attr.status = "在线";
        attr.waterlevel = (getRandomInt(20) + Math.random() + 300).toFixed(2);
        attr.monthwater = "320/300";
        attr.datewater = "318.5/316.7";
        
        let corrdinate = eachdata.geometry.coordinates;
        let pointgraphic = AddGraphic.addDemoGraphic1(layercluster, corrdinate,waterlevel);
        layercluster.addGraphic(pointgraphic);
        totalData.push(attr);
        tableData.value = JSON.parse(JSON.stringify(totalData.slice(0, pagerow.value)));
        pagenumber.value = totalData.length;

        //addRandomGraphicByCount(corrdinate,attr.waterlevel)

        const inthtml = `<table style="width: auto;color:black;border-radius: 5px;">
                <tr>
                <th scope="col" colspan="2" style="text-align:center;font-size:15px;background-color:#EDF4FF">信息</th>
                </tr>
                <tr>
                <td>硬件编号：</td>
                <td>${attr.number}</td>
                </tr>
                <tr>
                <td>当前水位：</td>
                <td>${attr.waterlevel}</td>
                </tr>
            </table>`;

        pointgraphic.bindPopup(inthtml);
    }
}


function addRandomGraphicByCount(position, attr) {
  const graphic = new mars3d.graphic.DivGraphic({
    position,
    style: {
      html: `<div style="width: 80px;height:80px;"></div>`,
      horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
      verticalOrigin: Cesium.VerticalOrigin.BOTTOM
    },
    attr
  })
  graphic.on(mars3d.EventType.load, function (e) {
    const dom = e.target.container.firstChild
    const attr = e.target.attr

    const liquidfillchartChart = echarts.init(dom)

    // 参考API：https://github.com/ecomfe/echarts-liquidfill
    // 参考示例：https://www.makeapie.com/explore.html#tags=liquidFill~sort=rank~timeframe=all~author=all
    const option = {
      series: [
        {
          type: "liquidFill",
          radius: "100%",
          outline: { show: false },
          color: ["#fb980b"],
          data: [attr],
          label: {
            color: "#294D99",
            insideColor: "#fff",
            fontSize: 20
          }
        }
      ]
    }
    liquidfillchartChart.setOption(option)
  })
  graphicLayer.addGraphic(graphic)
}


function changePage() {
  console.log(currentPage.value);
}

// 关闭主页面表单
function closePanel() {
  panelshow.value = false;
}

const sideClick = (data) => {
  if (data.index == "/dataAnalysis/monitor/waterlevel") panelshow.value = true;
};
store.changeSide(sideClick);


function clearSearch(){
    hardwarenumber.value = "";
    hardwaretype.value = "";
    hardwareposition.value = "";
}

function switchImageLayer() {
  if (imagemap.value) {
    map.addLayer(tileLayer);
  } else {
    map.removeLayer(tileLayer);
  }
}

function switchPipLine() {
  if (pipemap.value) {
    map.addLayer(wmsLayer);
  } else {
    map.removeLayer(wmsLayer);
  }
}

onMounted(async () => {
  map = new mars3d.Map("mars3dcontent", mapOptions);
  map.addLayer(layerpoint);
  map.addLayer(layercluster);
  map.addLayer(graphicLayer);
  getWaterPoint();
  bindMapDefault(map);
});

onUnmounted(() => {
  destroyMap(map);
});
</script>

<style scoped>
.container {
  width: 100%;
  height: 100%;
  background-color: antiquewhite;
}

#mars3dcontent {
  width: 100%;
  height: 100%;
}

.layercontrol {
  position: fixed;
  top: 10vh;
  right: 10vh;
  width: 20vh;
  height: 10vh;
  border-radius: 1vh;
  background-color: white;
  z-index: 99;
  display: flex;
  flex-direction: column;
  justify-content: space-evenly;
  align-items: flex-start;
}

.item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}
.tablecontainer {
  position: absolute;
  display: flex;
  justify-content: center;
  align-items: center;
  bottom: 0px;
  width: 100%;
  height: 40%;
  z-index: 99;
}

.el-input-number {
  width: 70px;
  text-align: left;
}

.el-input-number :deep(.el-input__wrapper) {
  padding-right: 0px;
  padding-left: 0px;
}

.el-input-number :deep(.el-input__inner) {
  text-align: left;
  text-indent: 5px;
}

.tableForm {
  width: 90%;
  height: 95%;
  background-color: white;
  border-radius: 1vh;
  z-index: 99;
}

.form {
  margin-top: 20px;
  display: flex;
  height: 10%;
}

.tableposition {
  margin-top: 30px;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  flex-direction: column;
}

.page {
  margin-top: 15px;
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0px 30px;
}
.select {
  display: flex;
  width: 70%;
  flex-wrap: nowrap;
  justify-content: space-evenly;
  align-items: center;
}

.bottomlist {
  display: flex;
  width: 30%;
  flex-wrap: nowrap;
  justify-content: space-evenly;
  align-items: center;
}

/* Pop关闭按钮 */
.container :deep(.closeButton) {
  color: black;
}
.container :deep(.mars3d-popup-content) {
  margin: 0px;
  border-radius: 5px;
}
.container :deep(.mars3d-popup-background) {
  border-radius: 10px;
}

.el-table th {
  background-color: antiquewhite;
}

.el-dropdown-item {
  display: flex;
}
.div-button {
  cursor: pointer;
}
.el-button {
  width: 100px;
}
</style>
